<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/21
 * Time: 14:16
 */

namespace app\index\controller;


use app\common\utils\PHPExcelUtils;
use MongoDB\Driver\Manager;
use MongoDB\Collection;
use think\Controller;

class MongoTest extends Controller
{
    protected $mongoManager;
    protected $mongoCollection;
    public function __construct()
    {
        $this->mongoManager = new Manager($this->getUri());
        $this->mongoCollection = new Collection($this->mongoManager, "qusetion","quizzes");
    }
    public function find(){
        $data = $this->mongoCollection->findOne();
        $array = (array)$data;
        var_dump($array['answer']);
        var_dump($data);
        var_dump($array['options']);
    }

    public function test() {
        // 读取一条数据
        $data = $this->mongoCollection->find();
        $cellList = array('题目', '类别', '子类别','答案','选项1','选项2','选项3','选项4');
        $phpExcelUtil = new PHPExcelUtils();
        $obj = $phpExcelUtil->setCellList($cellList);
        $objSheet = $obj->getActiveSheet();
        $row =2;
        //数组内一些字段转成中文
        foreach ($data as $key=>$value){
            $array = (array)$value;
            $objSheet->setCellValue('A'.$row, $array['quiz']);
            $objSheet->setCellValue('B'.$row, $array['school']);
            $objSheet->setCellValue('C'.$row, $array['type']);
            $objSheet->setCellValue('D'.$row, $array['answer']);
            $options = (array)$array['options'];
            $objSheet->setCellValue('E'.$row, $options[0]);
            $objSheet->setCellValue('F'.$row, $options[1]);
            $objSheet->setCellValue('G'.$row, $options[2]);
            $objSheet->setCellValue('H'.$row, $options[3]);
            $row ++;
        }

        $fileName = iconv("utf-8", "gb2312", '题库.xls');
        $obj->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
    protected function getUri()
    {
        return getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1:27017';
    }
}